<?php

namespace app\index\model;

use think\Model;

class Cart extends Model
{
    // 添加到购物车 并存到数据库中
    public static function addCart($goods_id,$cart_number,$goods_attr_ids)
    {

        $user_id = session("index_user.id");

        $where = [
            'user_id' => $user_id,
            'goods_id' => $goods_id,
            'goods_attr_ids' => $goods_attr_ids
        ];

        $data = self::where($where)->find();

        if($data){

            $data->cart_number += $cart_number;
            $data->save();

        }else{

            $where['cart_number'] = $cart_number;
            self::create($where,true);
        }
    }

    //查询当前用户所有的购物车内容
    public static function getAllCart()
    {
        $user_id = session("index_user.id");

        $data = self::where("user_id",$user_id)->select();

        // 将获取到的数据转换成标准的数组格式
        foreach($data as &$v){
            $v = $v->toArray();
        }

        return $data;
    }

    // 获取所有要购买的数据
    public static function getGoods($cart_ids)
    {
        return self::alias("c")
            ->field('c.*,g.goods_name,g.goods_price,g.goods_logo,g.goods_number')
            ->join('think_goods g','c.goods_id = g.id','left')
            ->where("c.id",'in',$cart_ids)
            ->select();
    }
}
